<template>
    <view class="topic-square-detail">  
        <headerVue :back="true" bgColor="transparent"/>
         <!-- 主图区域 -->
         <view class="main-image-section">
            <swiper 
                class="main-image-swiper"
                :indicator-dots="false"
                :duration="500"
                style="width:100%;height:480rpx;"
            >
                <swiper-item v-for="(img, idx) in detail.image_urls" :key="idx">
                    <u-image 
                        :src="img" 
                        mode="aspectFill" 
                        width="100%" 
                        height="480rpx"
                        radius="0"
                    ></u-image>
                </swiper-item>
            </swiper>
        </view>
        <view class="content-section">
            <view class="content-header">
                <u-image :src="IMAGE_URL + '/static/community/icon18.png'" width="32rpx" height="32rpx"></u-image>
                <view class="content-title">{{ detail.title }}</view>
            </view>
            <view class="author-info">
                <view class="author-info-item">
                    <view class="author-info-item-avatar">
                        <u-image :src="detail.pic" width="32rpx" height="32rpx"></u-image>
                    </view>
                    <view class="author-info-item-name">{{ detail.author_name }}</view>
                    <view class="author-info-item-time">{{ detail.publish_time }}</view>
                </view>
            </view>
            <view class="content-content">
                <u-parse :content="detail.content" />
            </view>
        </view>
        <footerVue>
            <view class="interaction-footer">
                <view class="input-section" @click="openCommentInput">
                    <u-textarea 
                        class="comment-input" 
                        v-model="commentValue" 
                        placeholder="Hi~ 说点什么吧..." 
                        height="68rpx" 
                        :auto-height="true"
                        @click="openCommentInput">
                    ></u-textarea>
                </view>
                <view class="action-section">
                    <view class="action-item">
                        <u-icon name="share-square" color="#333333" size="35rpx"></u-icon>
                        <text class="action-text">{{ detail.view_count}}</text>
                    </view>
                    <view class="action-item" @click="handleLike">
                        <u-icon :name="detail.is_collect ? 'star-fill' : 'star'" :color="detail.is_collect ? '#fc0808' : '#333333'" size="35rpx"></u-icon>
                        <text class="action-text">{{detail.collect_count}}</text>
                    </view>
                    <view class="action-item" @click="handleComment">
                        <u-icon name="chat" color="#333333" size="35rpx"></u-icon>
                        <text class="action-text">{{detail.comment_count }}</text>
                    </view>
                </view>
            </view>
        </footerVue>
        
        <!-- 评论弹窗 -->
        <comment-pop 
            :show="commentPopupShow" 
            :postId="detail.id" 
            :commentCount="detail.comment_count"
            :noCommentList="noCommentList"
            :commentList="commentList"
            :commentTotal="commentTotal"
            :commentHasMore="commentHasMore"
            :commentLoading="commentLoading"
            :replyLoadingMap="replyLoadingMap"
            :keyboardHeight="keyboardHeight"
            :postOwnerName="detail.author_name"
            @close="closeCommentPopup"
            @comment-added="onCommentAdded"
            @load-more-comments="loadMoreComments"
            @reply-to-comment="replyToComment"
            @toggle-replies="toggleReplies"
            @send-comment="handleSendComment"
            @keyboard-height-change="onKeyboardHeightChange"
        />
    </view>
</template>
<script>
import headerVue from '@/components/header.vue'
import { getCommunitynewsTopicDetail, postCommunitynewsTopicFavorite, postCommunitynewsTopicUnfavorite, getCommunitynewsCommentsReplies, getCommunitynewsTopicComments, postCommunitynewsTopicCommentsAdd } from '@/api/index.js'
import { formatPublishTime, formatNumber } from '@/utils/utils.js'
import footerVue from '@/components/fixed-footer/index.vue'
import CommentPop from '@/components/comment-pop/index.vue'
import appConfig from '@/config/app.js'
export default {
    components: { headerVue, footerVue, CommentPop },
    data() {
        return {
            IMAGE_URL: appConfig.IMAGE_URL,
            id: '',
            detail: {},
            commentValue: '',
            commentPopupShow: false,
            noCommentList: false,
            // 评论相关数据
            commentList: [],
            commentTotal: 0,
            commentPage: 1,
            commentLimit: 10,
            commentHasMore: true,
            commentLoading: false,
            // 回复相关
            replyLoadingMap: {},
            loadedRepliesMap: {},
            replyPageMap: {},
            // 键盘高度
            keyboardHeight: 0,
        }
    },
    onLoad(option) {
        this.getCommunitynewsTopicDetailEvent(option.id)
    },
    methods: {
        async getCommunitynewsTopicDetailEvent(id) {
            const res = await getCommunitynewsTopicDetail({id})
            const list = res.data || {}
            // 后端可能返回字符串/空/null/数组，统一为数组
            let imgs = []
            const raw = list.image_urls
            if (Array.isArray(raw)) {
                imgs = raw
            } else if (typeof raw === 'string') {
                const s = raw.trim()
                if (s) {
                    try {
                        const parsed = JSON.parse(s)
                        if (Array.isArray(parsed)) imgs = parsed
                    } catch (e) {
                        // 非JSON字符串，尝试逗号分隔
                        imgs = s.includes(',') ? s.split(',').map(x => x.trim()).filter(Boolean) : (s ? [s] : [])
                    }
                }
            }
            list.image_urls = imgs
            // 格式化为“YYYY年MM月DD日 HH:mm”
            if (list.publish_time) {
                list.publish_time = formatPublishTime(list.publish_time, 'YYYY年MM月DD日 HH:mm')
            }
            list.view_count = formatNumber(list.view_count)
            list.collect_count = formatNumber(list.collect_count)
            list.comment_count = formatNumber(list.comment_count)
            this.detail = list
        },
        openCommentInput() {
            // 直接评论模式
            this.noCommentList = true
            this.commentPopupShow = true
        },
        
        closeCommentPopup() {
            this.commentPopupShow = false
            // 重置评论相关状态
            this.commentList = []
            this.commentTotal = 0
            this.commentPage = 1
            this.commentHasMore = true
            this.commentLoading = false
            this.replyLoadingMap = {}
            this.loadedRepliesMap = {}
            this.replyPageMap = {}
            this.keyboardHeight = 0
        },
        
        // 评论添加成功后的回调
        onCommentAdded() {
            // 更新话题评论数
            this.detail.comment_count = (this.detail.comment_count || 0) + 1
        },

        // 加载更多评论
        loadMoreComments() {
            this.getCommentList()
        },

        // 回复评论
        replyToComment(comment) {
            // 如果是回复二级评论，需要确保其父评论的回复列表已加载
            if (!comment.member) {
                // 这是二级评论，需要找到其父评论并确保回复列表已加载
                this.ensureParentCommentRepliesLoaded(comment)
            }
        },

        // 切换回复展开状态
        toggleReplies(comment) {
            if (this.replyLoadingMap[comment.id]) return
            
            if (comment.expanded) {
                if (this.replyPageMap[comment.id] && 
                    this.loadedRepliesMap[comment.id] && 
                    this.loadedRepliesMap[comment.id].length < comment.reply_count) {
                    this.loadReplies(comment)
                    return
                }
                this.$set(comment, 'expanded', false)
                return
            }
            
            if (this.loadedRepliesMap[comment.id] && this.loadedRepliesMap[comment.id].length > 0) {
                this.$set(comment, 'expanded', true)
                this.$set(comment, 'replies', this.loadedRepliesMap[comment.id])
                return
            }
            
            this.$set(comment, 'expanded', true)
            this.$set(comment, 'replies', [])
            this.loadReplies(comment)
        },

        // 处理发送评论
        handleSendComment(data) {
            const { content, parentId } = data
            
            uni.showToast({ icon: 'loading' })
            
            postCommunitynewsTopicCommentsAdd({
                topic_id: this.detail.id,
                content: content,
                parent_id: parentId
            }).then((res) => {
                uni.hideToast()
                if (res && res.errno === 0) {
                    uni.showToast({ title: '已发送', icon: 'none' })
                    
                    // 本地插入新评论数据
                    this.insertNewCommentLocally(res.data.comment_id, content, parentId)
                    
                    // 更新话题评论数
                    this.onCommentAdded()
                }
            }).catch(() => {
                uni.hideToast()
                uni.showToast({ title: '发送失败', icon: 'none' })
            })
        },

        // 键盘高度变化
        onKeyboardHeightChange(height) {
            this.keyboardHeight = height
        },
        async handleLike() {
            // 点赞功能
            if (this.detail.is_collect) {
                await postCommunitynewsTopicUnfavorite({id: this.detail.id})
                this.detail.is_collect = false
                this.detail.collect_count = Math.max(0, (this.detail.collect_count || 0) - 1)
            } else {
                await postCommunitynewsTopicFavorite({id: this.detail.id})
                this.detail.is_collect = true
                this.detail.collect_count = (this.detail.collect_count || 0) + 1
            }
        },
        
        handleComment() {
            // 评论区评论模式
            this.noCommentList = false
            this.commentPopupShow = true
            this.commentTotal = this.detail.comment_count
            this.commentPage = 1
            this.commentHasMore = true
            this.commentList = []
            this.replyLoadingMap = {}
            this.loadedRepliesMap = {}
            this.replyPageMap = {}
            
            // 获取评论列表
            this.getCommentList()
        },

        // 获取评论列表
        getCommentList() {
            if (this.commentLoading || !this.commentHasMore) return
            
            this.commentLoading = true
            getCommunitynewsTopicComments(this.detail.id, {
                page: this.commentPage,
                limit: this.commentLimit
            }).then((res) => {
                if (res && res.errno === 0) {
                    const list = res.data?.list || []
                    
                    // 为每条评论添加本地状态字段
                    const processedList = list.map((item) => {
                        if (typeof item.expanded === 'undefined') {
                            item.expanded = false
                        }
                        if (typeof item.replies === 'undefined') {
                            item.replies = []
                        }
                        return item
                    })
                    
                    if (this.commentPage === 1) {
                        this.commentList = processedList
                    } else {
                        this.commentList = this.commentList.concat(processedList)
                    }
                    
                    // 判断是否还有更多
                    const total = res.data?.pagination?.total
                    if (typeof total === 'number') {
                        this.commentHasMore = this.commentList.length < total
                    } else {
                        this.commentHasMore = list.length >= this.commentLimit
                    }
                    
                    if (this.commentHasMore) {
                        this.commentPage += 1
                    }
                }
            }).finally(() => {
                this.commentLoading = false
            })
        },

        // 加载回复
        loadReplies(comment) {
            if (this.replyLoadingMap[comment.id]) return
            
            const commentId = comment.id
            const page = this.replyPageMap[commentId] || 1
            
            this.$set(this.replyLoadingMap, commentId, true)
            
            getCommunitynewsCommentsReplies(commentId,{
                page: page,
                limit: 10
            }).then((res) => {
                if (res.errno === 0) {
                    const newReplies = res.data?.list || []
                    const total = res.data?.total || 0
                    
                    if (page === 1) {
                        const existingLocalReplies = this.loadedRepliesMap[commentId] || []
                        const localReplies = existingLocalReplies.filter(reply => reply.isLocalInsert)
                        
                        const filteredServerReplies = newReplies.filter(serverReply => {
                            return !localReplies.some(localReply => localReply.id === serverReply.id)
                        })
                        
                        this.loadedRepliesMap[commentId] = [...localReplies, ...filteredServerReplies]
                        this.$set(comment, 'replies', [...this.loadedRepliesMap[commentId]])
                    } else {
                        const existingReplies = this.loadedRepliesMap[commentId] || []
                        const existingIds = existingReplies.map(reply => reply.id)
                        
                        const filteredNewReplies = newReplies.filter(serverReply => {
                            return !existingIds.includes(serverReply.id)
                        })
                        
                        this.loadedRepliesMap[commentId] = existingReplies.concat(filteredNewReplies)
                        this.$set(comment, 'replies', [...this.loadedRepliesMap[commentId]])
                    }
                    
                    if (this.loadedRepliesMap[commentId].length < total) {
                        this.replyPageMap[commentId] = page + 1
                    } else {
                        delete this.replyPageMap[commentId]
                    }
                    
                    this.$set(comment, 'expanded', true)
                }
            }).catch((err) => {
                console.error('加载回复失败:', err)
                uni.showToast({ title: '加载回复失败', icon: 'none' })
            }).finally(() => {
                this.$set(this.replyLoadingMap, commentId, false)
            })
        },

        // 确保父评论的回复列表已加载
        ensureParentCommentRepliesLoaded(replyComment) {
            // 在commentList中查找包含该回复的一级评论
            for (const comment of this.commentList) {
                if (comment.replies && comment.replies.length > 0) {
                    const foundReply = comment.replies.find(reply => reply.id === replyComment.id)
                    if (foundReply) {
                        // 找到父评论，确保其回复列表已加载到loadedRepliesMap中
                        if (!this.loadedRepliesMap[comment.id]) {
                            this.loadedRepliesMap[comment.id] = [...comment.replies]
                        }
                        break
                    }
                }
            }
            
            // 如果还是没有找到，尝试强制加载
            if (Object.keys(this.loadedRepliesMap).length === 0) {
                // 遍历所有有回复的评论，强制加载回复列表
                for (const comment of this.commentList) {
                    if (comment.reply_count > 0 && !this.loadedRepliesMap[comment.id]) {
                        this.loadReplies(comment)
                    }
                }
            }
        },

        // 本地插入新评论
        insertNewCommentLocally(commentId, content, parentId) {
            const userInfo = this.$store.state.userInfo
            const currentTime = new Date().toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            }).replace(/\//g, '-')
            
            if (parentId === 0) {
                // 一级评论
                const newComment = {
                    id: commentId,
                    content: content,
                    create_time: currentTime,
                    member: {
                        nickname: userInfo?.nickname || '用户'
                    },
                    userpic: userInfo?.userpic || '/static/mine/title-icon.png',
                    reply_count: 0,
                    expanded: false,
                    replies: []
                }
                
                this.commentList.unshift(newComment)
                this.commentTotal += 1
                
            } else {
                // 二级回复：需要找到对应的父评论
                let parentComment = null
                let replyToComment = null
                
                // 首先尝试在commentList中查找（回复一级评论的情况）
                parentComment = this.commentList.find(comment => comment.id === parentId)
                
                if (parentComment) {
                    // 回复一级评论
                    replyToComment = parentComment
                } else {
                    // 回复二级评论，需要在所有已加载的回复中查找
                    for (const firstLevelCommentId in this.loadedRepliesMap) {
                        const replies = this.loadedRepliesMap[firstLevelCommentId] || []
                        const foundReply = replies.find(reply => reply.id === parentId)
                        if (foundReply) {
                            // 找到被回复的二级评论，其父评论就是firstLevelCommentId对应的评论
                            parentComment = this.commentList.find(comment => comment.id === firstLevelCommentId)
                            replyToComment = foundReply
                            break
                        }
                    }
                    
                    // 如果还是没找到，尝试在commentList的replies中查找
                    if (!parentComment) {
                        for (const comment of this.commentList) {
                            if (comment.replies && comment.replies.length > 0) {
                                const foundReply = comment.replies.find(reply => reply.id === parentId)
                                if (foundReply) {
                                    parentComment = comment
                                    replyToComment = foundReply
                                    break
                                }
                            }
                        }
                    }
                }
                
                if (parentComment) {
                    // 创建二级回复数据结构
                    const newReply = {
                        id: commentId,
                        content: content,
                        update_time: currentTime,
                        current_member: {
                            nickname: userInfo?.nickname || '用户'
                        },
                        userpic: userInfo?.userpic || '/static/mine/title-icon.png',
                        reply_member: {
                            nickname: replyToComment ? replyToComment.current_member?.nickname : parentComment.member?.nickname || '用户'
                        },
                        post_id: this.detail.id,
                        isLocalInsert: true
                    }
                    
                    // 确保父评论有replies数组
                    if (!parentComment.replies) {
                        this.$set(parentComment, 'replies', [])
                    }
                    
                    // 获取当前的replies数组
                    const currentReplies = [...(this.loadedRepliesMap[parentComment.id] || [])]
                    
                    // 找到被回复的评论在数组中的位置
                    let insertIndex = currentReplies.length
                    if (replyToComment) {
                        const replyIndex = currentReplies.findIndex(reply => reply.id === replyToComment.id)
                        if (replyIndex !== -1) {
                            // 插入到被回复的评论下面
                            insertIndex = replyIndex + 1
                        }
                    }
                    
                    // 在指定位置插入新回复
                    currentReplies.splice(insertIndex, 0, newReply)
                    
                    // 更新loadedRepliesMap
                    this.loadedRepliesMap[parentComment.id] = currentReplies
                    
                    // 更新父评论的replies数组
                    this.$set(parentComment, 'replies', [...currentReplies])
                    
                    // 更新回复数量
                    this.$set(parentComment, 'reply_count', (parentComment.reply_count || 0) + 1)
                    
                    // 更新评论总数（二级回复也算作评论）
                    this.commentTotal += 1
                    
                    // 如果父评论还没有展开，自动展开
                    if (!parentComment.expanded) {
                        this.$set(parentComment, 'expanded', true)
                    }
                    
                    // 管理分页状态
                    const totalLoadedReplies = this.loadedRepliesMap[parentComment.id].length
                    const totalReplyCount = parentComment.reply_count
                    
                    if (totalLoadedReplies >= totalReplyCount) {
                        delete this.replyPageMap[parentComment.id]
                    } else if (!this.replyPageMap[parentComment.id]) {
                        this.$set(this.replyPageMap, parentComment.id, 1)
                    }
                }
            }
        }
    }
}
</script>
<style lang="scss" scoped>
    .topic-square-detail {
        position: relative;
        width: 100%;
        min-height: 100vh;
    }

    // 主图区域
.main-image-section {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 480rpx;
    z-index: 1;
}

    .content-section {
        position: relative;
        width: 100%;
        height: 100%;
        z-index: 2;
        background-color: #fff;
        padding: 28rpx 32rpx;
        margin-top: 342rpx;
        box-sizing: border-box;
    }

    .content-header {
        position: relative;
        width: 100%;
        height: 100%;
        z-index: 2;
        display: flex;
        align-items: center;
    }

    .content-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-left: 12rpx;
    }

    .author-info {
        position: relative;
        width: 100%;
        z-index: 2;
        margin: 24rpx 0 28rpx;
    }

    .author-info-item {
        position: relative;
        width: 100%;
        z-index: 2;
        display: flex;
        align-items: center;
        justify-content: flex-start;
    }

    .author-info-item-avatar {
        position: relative;
        z-index: 2;
    }

    .author-info-item-name {
        position: relative;
        z-index: 2;
        margin:0 28rpx 0 4rpx;
        font-size: 24rpx;
        color: #999999;
    }

    .author-info-item-time {
        position: relative;
        z-index: 2;
        font-size: 24rpx;
        color: #999999;
    }
    
    // 底部交互栏样式
    .interaction-footer {
        display: flex;
        align-items: center;
        justify-content: space-between;
        background: #fff;
    }
    
    .input-section {
        width: 392rpx;
        height: 72rpx;
        background: #F6F6F6;
        border-radius: 60rpx 60rpx 60rpx 60rpx;
    }
    
    .comment-input {
        width: 392rpx;
        background: #F6F6F6;
        border-radius: 60rpx 60rpx 60rpx 60rpx;
        padding: 12rpx 24rpx;
        box-sizing: border-box;
        font-size: 26rpx;
        color: #999;
        min-height: 68rpx;
        line-height: 1.4;
    }
    
    .action-section {
        display: flex;
        align-items: center;
        gap: 20rpx;
    }
    
    .action-item {
        display: flex;
        align-items: center;
        gap: 8rpx;
    }
    
    .action-text {
        font-size: 24rpx;
        color: #333;
        font-weight: 500;
    }
</style>